<?php

namespace core;

class Validator {
    protected $rules = [];
    protected $errors = [];
    protected $data = [];
    
    public function __construct($data = []) {
        $this->data = $data;
    }
    
    public function rules(array $rules) {
        $this->rules = $rules;
        return $this;
    }
    
    public function validate() {
        foreach ($this->rules as $field => $rules) {
            $value = $this->data[$field] ?? null;
            
            foreach ($rules as $rule => $params) {
                if (is_numeric($rule)) {
                    $rule = $params;
                    $params = [];
                }
                
                if (!$this->checkRule($field, $value, $rule, $params)) {
                    return false;
                }
            }
        }
        return true;
    }
    
    protected function checkRule($field, $value, $rule, $params) {
        switch ($rule) {
            case 'required':
                if (empty($value)) {
                    $this->errors[$field][] = '此字段为必填项';
                    return false;
                }
                return true;
            
            case 'email':
                if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                    $this->errors[$field][] = '请输入有效的邮箱地址';
                    return false;
                }
                return true;
            
            case 'min':
                if (strlen($value) < $params[0]) {
                    $this->errors[$field][] = "长度不能少于{$params[0]}个字符";
                    return false;
                }
                return true;
            
            // 更多验证规则...
            
            default:
                return true;
        }
    }
    
    public function errors() {
        return $this->errors;
    }
}